/*
 * Copyright(c) 2018-? the original author[Wien(luweien@aliyun.com)] or authors.
 *
 */
package org.doll.it.web.config;

import java.time.Duration;

import org.doll.it.base.constant.DefaultConsts;
import org.doll.it.web.interceptor.ApiInterceptor;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Web MVC配置
 * 
 * @author Wien(luweien@aliyun.com)
 *
 */
@Configuration
@ServletComponentScan(DefaultConsts.PACKAGE_PREFIX)
public class WebMvcConfig implements WebMvcConfigurer {

	@Bean
	public HandlerInterceptor getApiInterceptor() {
		return new ApiInterceptor();
	}

	/**
	 * 添加自定义拦截器
	 */
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		// 添加自定义拦截器，拦截所有的API的请求
		registry.addInterceptor(getApiInterceptor()).addPathPatterns(DefaultConsts.API_PATH_PREFIX + "**");
	}

	/**
	 * 支持跨域访问
	 */
	@Override
	public void addCorsMappings(CorsRegistry registry) {
		registry.addMapping("/**").allowedOrigins("*").allowCredentials(true).allowedMethods("*")
				.maxAge(Duration.ofHours(1).getSeconds());
	}

}
